<?php

namespace App\Services\Platform;

use App\Services\Service;
use App\Services\Traits\DatabaseMysql;
use App\Mappers\Platform\UserMapper;
use App\Models\Agency\Auth\User;

class UserService extends Service
{
    use DatabaseMysql;

    /**
     * 获取数据列表
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Database\Eloquent\Collection[]|int[]
     */
    public function getList($request)
    {
        $query = User::query();

        // 筛选【平台】
        $this->makeWhereParam($request, 'org_id', $query);
        // 软删除筛选
        $this->makeWhereDeleted($request, $query);
        // 邮箱左搜索
        $this->makeWhereParamLike($request, 'keyword', $query, 'email');

        // 数据条数
        $total = (clone $query)->count();
        // 排序分页
        $this->makeOrderParam($request, $query)->makePaginationParam($request, $query);
        // 查询数据
        $collection = $query->get()->makeVisible('is_super_admin');

        return [
            $collection,
            $total
        ];
    }

    /**
     * 保存数据
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \App\Models\Agency\Auth\User
     */
    public function saveItem($request, $id = null)
    {
        // 数据映射
        $data = UserMapper::make($request)->toArray();

        // 用户模型
        $user = User::withTrashed()->findOrNew($id);
        // 保存数据
        $user->fill($data)->save();

        // 超级管理员
        if ((boolean)$request->input('is_super_admin')) {
            $user->assignSuperAdmin();
        } else {
            $user->removeSuperAdmin();
        }

        return $user;
    }
}
